﻿$.prototype.toJSON = function(data){
    return JSON.parse(data);
}

//IMCIS项目的命名空间
imcis = {};

//通用jQuery的ajax方法。参数如下：
//url:ajax请求地址。
//data:ajax参数。
//async:是否异步，true为异步，false为同步。
//successFn:成功的回调函数。
//errorFn:异常的回调函数。
imcis.ajax = function (url, data, async, successFn, errorFn, beforeFn, completeFn) {
    var id = (new Date()).getTime();
    var setting = {
        type: "POST",
        url: url,
        dataType: "json",
        async: async,
        contentType: 'application/json',
        data: JSON.stringify(data),
        success: function (returnData) {
            successFn(returnData);
        },
        error: function (xhr, textStatus, errorThrown) {
            if (errorFn) {
                errorFn(xhr, textStatus, errorThrown);
            } else {
                //imcis.ajaxError(xhr, "异常", "");
            }
            imcis.wait.end();
        },
        beforeSend: function (xhr) {
            if (beforeFn) {
                beforeFn();
            } else {
                imcis.wait.start();
            }
        },
        complete: function (xhr) {
            if (completeFn) {
                completeFn();
            }
            imcis.wait.end();
        }
    };

    $.ajax(setting);
};

imcis.debounce = function(func, threshold, execAsap) {
	var timeout;

	return function debounced() {
		var obj = this, args = arguments;

		function delayed() {
			if (!execAsap)
				func.apply(obj, args);
			timeout = null;
		}

		if (timeout)
			clearTimeout(timeout);
		else if (execAsap)
			func.apply(obj, args);

		timeout = setTimeout(delayed, threshold || 500);
	};
};

imcis.parseURL = function(url) {
	var a = document.createElement('a');
	a.href = url;
	return {
		source: url,
		protocol: a.protocol.replace(':', ''),
		host: a.hostname,
		port: a.port,
		query: a.search,
		params: (function() {
			var ret = {},
				seg = decodeURI(a.search).replace(/^\?/, '').split('&'),
				len = seg.length, i = 0, s;
			for (; i < len; i++) {
				if (!seg[i]) {
					continue;
				}
				s = seg[i].split('=');
				ret[s[0]] = decodeURIComponent(s[1]);
			}
			return ret;
		})(),
		file: (a.pathname.match(/\/([^\/?#]+)$/i) || [, ''])[1],
		hash: a.hash.replace('#', ''),
		path: a.pathname.replace(/^([^\/])/, '/$1'),
		relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [, ''])[1],
		segments: a.pathname.replace(/^\//, '').split('/')
	};
};

imcis.convertDateFromJson = function (jsonDate, shortDate) {
    // jsonDate format "/Date(1245398693390)/"; 
    if (!jsonDate)
        return "";

    if (jsonDate.indexOf('/Date') != 0) {
        return jsonDate;
    }

    var date = new Date(parseInt(/-?\d+/.exec(jsonDate)[0]));
    var dateString = date.getFullYear() + "-"
		+ ((date.getMonth() + 1) < 10 ? "0" + (date.getMonth() + 1) : (date.getMonth() + 1)) + "-"
		+ (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " "
		+ (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":"
		+ (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes());

    if (shortDate) {
        return dateString.substring(0, 10);
    }
    return dateString;
};

imcis.wait = {
    lading: '',
    index: null,
    start: function ($obj) {
        if (imcis.browser.versions.mobile && !imcis.versionCompare(layer.v, '2.0')) {
           imcis.wait.index = layer.open({ type: 2, time: 10*1000 });
        } else {
           imcis.wait.loading = layer.load(1, { shade: [0.4, '#333'] });
        }
    },
    end: function () {
        if (imcis.browser.versions.mobile && !imcis.versionCompare(layer.v, '2.0')) {
            try {
                layer.close(imcis.wait.index);
            } catch (e) { };

            return false;
        } else {
            layer.close(imcis.wait.loading);
        }
    }
};

imcis.json = {
    parse: function (sJSON) {
        if (window.JSON) {
            return window.JSON.parse(sJSON);
        } else {
            return eval('(' + sJSON + ')');
        }
    },
    stringify: function (value) {
        if (window.JSON) {
            return window.JSON.stringify(value);
        } else {
            var toString = Object.prototype.toString;
            var isArray = Array.isArray || function (a) { return toString.call(a) === '[object Array]'; };
            var escMap = { '"': '\\"', '\\': '\\\\', '\b': '\\b', '\f': '\\f', '\n': '\\n', '\r': '\\r', '\t': '\\t' };
            var escFunc = function (m) { return escMap[m] || '\\u' + (m.charCodeAt(0) + 0x10000).toString(16).substr(1); };
            var escRE = /[\\"\u0000-\u001F\u2028\u2029]/g;

            if (value == null) {
                return 'null';
            } else if (typeof value === 'number') {
                return isFinite(value) ? value.toString() : 'null';
            } else if (typeof value === 'boolean') {
                return value.toString();
            } else if (typeof value === 'object') {
                if (typeof value.toJSON === 'function') {
                    return imcis.json.stringify(value.toJSON());
                } else if (isArray(value)) {
                    var res = '[';
                    for (var i = 0; i < value.length; i++)
                        res += (i ? ', ' : '') + imcis.json.stringify(value[i]);
                    return res + ']';
                } else if (toString.call(value) === '[object Object]') {
                    var tmp = [];
                    for (var k in value) {
                        if (value.hasOwnProperty(k))
                            tmp.push(imcis.json.stringify(k) + ': ' + imcis.json.stringify(value[k]));
                    }
                    return '{' + tmp.join(', ') + '}';
                }
            }
            return '"' + value.toString().replace(escRE, escFunc) + '"';
        }
    }
};

imcis.date = {
    now: function () {
        var now = new Date();
        return "" + now.getFullYear() + "" +
			(now.getMonth() + 1) + "" +
			now.getDate() + "" +
			now.getHours() + "" +
			now.getMinutes() + "" +
			now.getSeconds() + "" +
			now.getMilliseconds();
    },
    dateStringFromDate: function (date) {
        if (!date) {
            return "";
        }
        date = new Date(date)
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var date = date.getDate();
        var dateString = year + "-" + (month < 10 ? "0" + month : month) + "-" + (date < 10 ? "0" + date : date);
        return dateString;
    }
};

//调用相机扫码
imcis.scan = {
    processedTime: 0,//积累Quagga.onProcessed执行次数
    init: function (callback, errorCallback) {
        if ($('#scanCamera').length == 0) {
            // opacity: 0.5;
            $('body').append('<div id="scanCamera"><img src="../Areas/ScheduleV2/Content/images/left.png" alt="返回" class="img-circle btn-back" style="width:60px;height:60px;z-index: 1000;"></div>');
        }

        $("#scanCamera .btn-back").unbind('click');
        $("#scanCamera .btn-back").click(function () {
            imcis.scan.close();
        });

        Quagga.init({
            inputStream: {
                name: "Live",
                type: "LiveStream",
                target: document.querySelector('#scanCamera')
            },
            decoder: {
                readers: ["code_128_reader"]
            }
        }, function (err) {
            if (err) {
                imcis.scan.close();
                if (errorCallback)
                    errorCallback(err);
                return
            }
            console.log("Quagga.js初始化完成，开始解析。");
            Quagga.start();
        });

        //循环执行解析Buffer
        Quagga.onProcessed(function (result) {
            if ($('#scanCamera').length == 0) {
                return;
            }
            $(".drawingBuffer")[0].height = $(".drawingBuffer")[0].height;
            var drawingCtx = Quagga.canvas.ctx.overlay,
                drawingCanvas = Quagga.canvas.dom.overlay;
            //canvas铺满全屏
            imcis.scan.resize(imcis.scan.processedTime);

            if (result) {
                if (result.box) {
                    Quagga.ImageDebug.drawPath(result.box, { x: 0, y: 1 }, drawingCtx, { color: "#00FF00", lineWidth: 2 });
                }
            }
            canvas = Quagga.canvas.dom.image.getContext("2d");
            var imageData = canvas.getImageData(0, 0, drawingCanvas.width, drawingCanvas.height);
            var code = jsQR(imageData.data, drawingCanvas.width, drawingCanvas.height, { inversionAttempts: "dontInvert", });
            var canvasQR = $(".drawingBuffer")[0].getContext("2d");

            if (code) {
                imcis.scan.drawLine(canvasQR, code.location.topLeftCorner, code.location.topRightCorner, "#00FF00");
                imcis.scan.drawLine(canvasQR, code.location.topRightCorner, code.location.bottomRightCorner, "#00FF00");
                imcis.scan.drawLine(canvasQR, code.location.bottomRightCorner, code.location.bottomLeftCorner, "#00FF00");
                imcis.scan.drawLine(canvasQR, code.location.bottomLeftCorner, code.location.topLeftCorner, "#00FF00");
                //二维码
                imcis.scan.checkResult(code.data,"QR" , callback);
            }
            imcis.scan.processedTime++;
        });
        //一维码
        Quagga.onDetected(function (data) {
            if (data.codeResult.code) {
                imcis.scan.checkResult(data.codeResult.code,"bar", callback);
            }
        });
    },
    drawLine: function (canvas, begin, end, color) {
        canvas.beginPath();
        canvas.moveTo(begin.x, begin.y);
        canvas.lineTo(end.x, end.y);
        canvas.lineWidth = 4;
        canvas.strokeStyle = color;
        canvas.stroke();
    },
    checkResult: function (code ,type ,callback) {
        imcis.scan.close();
        if (callback) {
            callback(code, type);
        }
    },
    resize: function (processedTime) {
        $('#scanCamera').children().each(function () {
            $(this).css({
                position: "absolute",
                left: $(this)[0].nodeName == "IMG" ? 10 : 0,
                top: $(this)[0].nodeName == "IMG" ? 10 : 0
            });
            var windowHeight = $(window).height();
            var windowWidth = $(window).width();
            if ($(this)[0].nodeName != "IMG" && (windowHeight != $(this).height() || windowWidth != $(this).width())) {
                if (processedTime == 0) {
                    $('body').append('<div class="scanCamera-backdrop" style="width:' + windowWidth + 'px;height:' + windowHeight + 'px;position:absolute;z-index:997;top:0;left:0;background-color: #000;" ></div>');
                }
                $(".scanCamera-backdrop").css({ "height": windowHeight + "px", "width": windowWidth + "px" });
                $(this).css({ "height": windowHeight + "px", "width": windowWidth + "px","z-index": "999" });
            }
        });
    },
    close: function () {
        Quagga.stop(); //关闭onProcessed
        imcis.scan.processedTime = 0;
        $("#scanCamera,.scanCamera-backdrop").remove();
    }
};


imcis.rsa = {
    encode: function (str, key) {
        var encryptor = new JSEncrypt();
        encryptor.setPublicKey(key);
        return encryptor.encrypt(str);
    },
    decode: function (str, key) {
        var decrypt = new JSEncrypt();
        decrypt.setPrivateKey(key);
        return decrypt.decrypt(str);
    }
}; 
imcis.aes = {
    getKey: function () {//获取16位秘钥
        var k = imcis.date.now();
        k = "tomtaw" + k.substr(k.length - 9) + parseInt(Math.random() * 10);
        return k;
    },
    encode: function (s, k) {
        if (!s || !k) {
            return "";
        }
        k = CryptoJS.enc.Utf8.parse(k);
        var encrypt = CryptoJS.AES.encrypt(s, k, {
            iv: k,
            mode: CryptoJS.mode.ECB,
            padding: CryptoJS.pad.Pkcs7
        });
        if (encrypt) {
            return encrypt.toString();
        } else {
            return "";
        }
    },
    decode: function (s, k) {
        if (!s || !k) {
            return "";
        }
        k = CryptoJS.enc.Utf8.parse(k);
        var decrypt = CryptoJS.AES.decrypt(s, k, {
            iv: k,
            mode: CryptoJS.mode.ECB,
            padding: CryptoJS.pad.Pkcs7
        });
        if (decrypt) {
            return decrypt.toString(CryptoJS.enc.Utf8)
        } else {
            return "";
        }
    }
};

imcis.schedule = {};
//获取元素在数组中的索引位置
imcis.schedule.indexOfByArrary = function (arr, tag) {
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] == tag)
            return i;
    }
    return -1;
};
imcis.schedule.getScheduleRouteStr = function (scheduleRoute) {
    //预约途径：1:诊间、2:预约中心、3:医技科室、4:自助机、5:手机端、6:自动、7:取排队号、8:互联网医院、9:区域预约、10:医共体预约。
    var scheduleRouteStr = "";
    if (typeof scheduleRoute != "number")
        scheduleRoute = parseInt(scheduleRoute);
    switch (scheduleRoute) {
        case 1: scheduleRouteStr = "诊间"; break;
        case 2: scheduleRouteStr = "预约中心"; break;
        case 3: scheduleRouteStr = "医技科室"; break;
        case 4: scheduleRouteStr = "自助机"; break;
        case 5: scheduleRouteStr = "手机端"; break;
        case 6: scheduleRouteStr = "自动"; break;
        case 7: scheduleRouteStr = "取排队号"; break;
        case 8: scheduleRouteStr = "互联网医院"; break;
        case 9: scheduleRouteStr = "区域预约"; break;
        case 10: scheduleRouteStr = "医共体预约"; break;
        default: break;
    }

    return scheduleRouteStr;
};
imcis.schedule.getSysParamValue = function (value, examType, patientClass) {
    examType = examType || '';
    patientClass = patientClass || '';
    value = value || '';

    if (!examType && !patientClass) {
        return value;
    }

    var paramList = value.split('|');
    if (paramList.length == 1) {
        var pList = paramList[0].split('=');
        if (pList.length == 1) {
            return value;
        }
        else {
            if (pList[0] == examType || pList[0] == patientClass || pList[0] == (examType + "+" + patientClass)
                || (pList[0].indexOf(examType + "+") > -1 && pList[0].indexOf(patientClass) > -1)) {
                return pList.length == 2 ? pList[1] : "";
            }
        }
    }
    else {
        for (var i = 0; i < paramList.length; i++) {
            var p = paramList[i];
            var pList = p.split('=');

            if (pList[0] == (examType + "+" + patientClass) || (pList[0].indexOf(examType + "+") > -1 && pList[0].indexOf(patientClass) > -1)) {
                return pList.length == 2 ? pList[1] : "";
            }
        }

        for (var i = 0; i < paramList.length; i++) {
            var p = paramList[i];
            var pList = p.split('=');

            if (pList[0] == examType) {
                return pList.length == 2 ? pList[1] : "";
            }
        }

        for (var i = 0; i < paramList.length; i++) {
            var p = paramList[i];
            var pList = p.split('=');

            if (pList[0] == patientClass) {
                return pList.length == 2 ? pList[1] : "";
            }
        }
    }

    return "";
},
imcis.schedule.getSysParamValueByOrg = function (value, organizationID, examType, patientClass) {
        value = value || '';
        organizationID = organizationID || '';
        examType = examType || '';
        patientClass = patientClass || '';

        var c1 = false, c2 = false, c3 = false;
        var paramList = value.split('|');

        for (var i = 0; i < paramList.length; i++) {
            var param = (paramList[i]).split('=');
            if (param.length == 1)
                return value;

            var p = param[0].split("+");
            switch (p.length) {
                case 1:
                    c1 = [organizationID, examType, patientClass].indexOf(param[0]) > -1;
                    c2 = c1;
                    c3 = c1;
                    break;
                case 2:
                    c1 = [organizationID, examType, patientClass].indexOf(p[0]) > -1;
                    c2 = [organizationID, examType, patientClass].indexOf(p[1]) > -1;
                    c3 = c1;
                    break;
                case 3:
                    c1 = [organizationID, examType, patientClass].indexOf(p[0]) > -1;
                    c2 = [organizationID, examType, patientClass].indexOf(p[1]) > -1;
                    c3 = [organizationID, examType, patientClass].indexOf(p[2]) > -1;
                    break;
            }

            if (c1 && c2 && c3)
                return param[1];
        }
        return '';
    },
imcis.schedule.getSysParamValueByServiceSectID = function (value, serviceSectID) {
    var result = "";
    if (value.indexOf("|") != -1) {
        var valueArr = value.split('|');
        for (var i = 0; i < valueArr.length; i++) {
            if (valueArr[i].indexOf('=') != -1) {
                var tempArr = valueArr[i].split('=');
                if (tempArr[0] == serviceSectID) {
                    result = tempArr[1];
                    break;
                }
            } else {
                result = valueArr[i];
            }
        }
    }
    else if (value.indexOf("=") != -1) {
        var tempArr = value.split('=');
        if (tempArr[0] == serviceSectID) {
            result = tempArr[1];
        }
    }
    else {
        result = value;
    }
    return result;
    };
imcis.schedule.getSysParamValueByScheduleRoute = function (value, scheduleRoute, examType, patientClass) {
    value = value || '';
    scheduleRoute = scheduleRoute || '';
    examType = examType || '';
    patientClass = patientClass || '';

    var c1 = false, c2 = false, c3 = false;
    var paramList = value.split('|');

    for (var i = 0; i < paramList.length; i++) {
        var param = (paramList[i]).split('=');
        if (param.length == 1)
            return value;

        var p = param[0].split("+");
        var arr = [scheduleRoute, examType, patientClass];
        switch (p.length) {
            case 1:
                c1 = imcis.schedule.indexOfByArrary(arr, p[0]) > -1;
                c2 = c1;
                c3 = c1;
                break;
            case 2:
                c1 = imcis.schedule.indexOfByArrary(arr, p[0]) > -1;
                c2 = imcis.schedule.indexOfByArrary(arr, p[1]) > -1;
                c3 = c1;
                break;
            case 3:
                c1 = imcis.schedule.indexOfByArrary(arr, p[0]) > -1;
                c2 = imcis.schedule.indexOfByArrary(arr, p[1]) > -1;
                c3 = imcis.schedule.indexOfByArrary(arr, p[2]) > -1;
                break;
        }

        if (c1 && c2 && c3)
            return param[1];
    }
    return '';
};
imcis.schedule.docScan = {
    absolutePath: "", 
    recepitQuery: {},
    recepitPicture: "",//保存签字单 
    getSchduleReceipt: function (image, familyShip) {
        var result = "";
        if (imcis.schedule.docScan.recepitQuery) {
            if (image) {
                image = image.replace(/^data:image\/\w+;base64,/, "");
                imcis.schedule.docScan.recepitQuery.patientSignature = image;
            }
            if (familyShip && familyShip != "本人") {
                familyShip = "(" + familyShip + "代)";
                imcis.schedule.docScan.recepitQuery.patientSignatureFamilyShip = familyShip;
            }
            imcis.ajax(imcis.schedule.docScan.absolutePath + "GetPrintExamScheduleReceipt", imcis.schedule.docScan.recepitQuery, false, function (ret) {
                if (ret.image) {
                    result = ret.image;
                } 
            });
        }
        if (!image) {
            imcis.schedule.docScan.recepitPicture = result;
        }
        return result;
    }
}

/*
$.cookie('username'); //获得cookie

$.cookie('username', '博客园'); //设置cookie
$.cookie('username', '小鱼儿博客园', { expires: 3 }); //设置带时间的cookie 3天

$.cookie('username', null); //删除 cookie
*/
jQuery.cookie = function (name, value, options) {

    if (typeof value != 'undefined') {

        options = options || {};

        if (value === null) {

            value = '';

            options.expires = -1;

        }

        var expires = '';

        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {

            var date;

            if (typeof options.expires == 'number') {

                date = new Date();

                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));

            } else {

                date = options.expires;

            }

            expires = ';expires=' + date.toUTCString();

        }

        var path = options.path ? ';path=' + options.path : '';

        var domain = options.domain ? ';domain=' + options.domain : '';

        var secure = options.secure ? ';secure' : '';

        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');

    } else {

        var cookieValue = null;

        if (document.cookie && document.cookie != '') {

            var cookies = document.cookie.split(';');

            for (var i = 0; i < cookies.length; i++) {

                var cookie = jQuery.trim(cookies[i]);

                if (cookie.substring(0, name.length + 1) == (name + '=')) {

                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));

                    break;

                }

            }

        }

        return cookieValue;

    }

};

//将cookie内容存入UserConfigMst表
imcis.cookie = {
    commonPath: "",
    setConfig: function (sName, sValue) {
        if (!imcis.cookie.commonPath) {
            return;
        }
        $.ajax({
            type: "POST",
            url: imcis.cookie.commonPath + "SaveUserConfig?t=" + imcis.date.now(),
            dataType: "json",
            async: true,
            contentType: 'application/json',
            data: JSON.stringify({ ConfigItemName: sName, ConfigItemValue: sValue, configByIP: true }),
            success: function () {
            },
            error: function () {
            },
        });
    },
    getConfig: function (sName) {
        if (!imcis.cookie.commonPath) {
            return "";
        }

        var value = "";
        $.ajax({
            type: "POST",
            url: imcis.cookie.commonPath + "GetUserConfig?t=" + imcis.date.now(),
            dataType: "json",
            async: false,
            contentType: 'application/json',
            data: JSON.stringify({ ConfigItemName: sName, queryByIP: true }),
            success: function (ret) {
                if (ret && ret.userConfig) {
                    value = ret.userConfig.ConfigItemValue;
                }
                //如果表中查不到，则尝试从本地获取cookie值
                if (!value) {
                    try {
                        value = $.cookie(name);
                    } catch (e) {
                        value = "";
                    }
                }
                if (!value) {
                    value = eWorld.cookie.getCookie(sName);
                }
            },
            error: function () {
                value = "";
            },
        });
        return value;

    }
};

//获取浏览器信息
imcis.browser = {
    versions: function () {
        var u = navigator.userAgent, app = navigator.appVersion;
        return {     //移动终端浏览器版本信息
            trident: u.indexOf('Trident') > -1, //IE内核
            presto: u.indexOf('Presto') > -1, //opera内核
            webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
            gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
            mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
            ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
            android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或uc浏览器
            iPhone: u.indexOf('iPhone') > -1, //是否为iPhone或者QQHD浏览器
            iPad: u.indexOf('iPad') > -1, //是否iPad
            webApp: u.indexOf('Safari') == -1 //是否web应该程序，没有头部与底部
        };
    }(),
    language: (navigator.browserLanguage || navigator.language).toLowerCase()
}

//版本号比较方法
imcis.versionCompare = function (curV, reqV) {
    if (curV && reqV) {
        //将两个版本号拆成数字
        var arr1 = curV.split('.'),
            arr2 = reqV.split('.');
        var minLength = Math.min(arr1.length, arr2.length),
            index = 0,
            diff = 0;
        //依次比较版本号每一位大小，当对比得出结果后跳出循环
        while (index < minLength && ((diff = parseInt(arr1[index]) - parseInt(arr2[index])) == 0)) {
            index++;
        }
        diff = (diff != 0) ? diff : (arr1.length - arr2.length);
        //若curV大于reqV，则返回true
        return diff > 0;
    } else {
        //输入为空
        return false;
    }
}

